import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zootix/constants/zt_constants.dart';
import 'package:zootix/screens/login/zt_confirm_agreement/zt_confirm_agreement.dart';
import 'package:zootix/store/zt_store.dart';
import 'package:zootix/zt_config.dart';
import 'package:zootix/constants/zt_router.dart';

import '../../util/zt_util.dart';

class ZtLoginController extends GetxController {
  final isAgreeTerm = RxBool(false);

  Future<void> appleLogin() async {
    await confirmAgreement().then((value) async {
      if (value != null) {
        AuthorizationCredentialAppleID? credential =
            await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
        );

        if (credential.identityToken != null) {
          await ZtAuthStore.to.login(ZtLoginEnum.fastLogin,
              identityToken: credential.identityToken);
        }
      }
    });
  }

  Future<void> fastLogin() async {
    await confirmAgreement().then((value) async {
      if (value != null) {
        await ZtAuthStore.to.login(ZtLoginEnum.fastLogin);
      }
    });
  }

  Future confirmAgreement() async {
    if (!isAgreeTerm.value) {
      return Get.defaultDialog(
          title: '',
          content: ZtConfirmAgreement(),
          titlePadding: const EdgeInsets.all(0));
    } else {
      return Future(() => true);
    }
  }

  Future<void> onPrivacyPolicyTap() async {
    ZtLogManger().putLog(
      ZtLogType.clickEvent,
      ZtLogManger.buildEvent(
          logType: ZtLogType.clickEvent, page: ZtLogPages.privacy),
    );
    launchUrl(Uri.parse(ZtGloablConfig.PRIVACY_POLICY));
  }

  Future<void> onTermTap() async {
    ZtLogManger().putLog(
      ZtLogType.clickEvent,
      ZtLogManger.buildEvent(
          logType: ZtLogType.clickEvent, page: ZtLogPages.terms),
    );
    launchUrl(Uri.parse(ZtGloablConfig.TERM_OF_USER));
  }
}
